package org.shiro.demo.util;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.shiro.demo.dao.util.QueryCondition;
import org.shiro.demo.entity.NotifyMessage;
import org.shiro.demo.service.IBaseService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
/**
 * @deprecated
 * @author Administrator
 *
 */
public class EhcacheUtils implements InitializingBean {

	private IBaseService baseService;
	private CacheManager manager;

	private Resource resource;

	@Override
	public void afterPropertiesSet() throws Exception {
		manager = CacheManager.create(new FileInputStream(resource.getFile()));

	}

	public int getManagerUnreadNum(long enterpriseId) {
		Cache cache1 = manager.getCache("countCache");

		String key = "e_unread" + enterpriseId;
		Element value = cache1.get(key);
		if (value == null) {
			int num = getCountFromMessage(enterpriseId + "");
			cache1.put(new Element(key, num));
			return num;
		} else {
			return (Integer) value.getObjectValue();
		}

	}

	// 从数据库更新
	// public void setEnterpriseUnreadNum(String enterpriseId) {
	// Cache cache1 = manager.getCache("countCache");
	// String key = "e_unread" + enterpriseId;
	// // Element value = cache1.get(key);
	// int num = getCountFromMessage(enterpriseId);
	// cache1.put(new Element(key, num));
	// }

	public void setManagerUnreadNum(long enterpriseId, int num) {
		Cache cache1 = manager.getCache("countCache");
		String key = "e_unread" + enterpriseId;
		// Element value = cache1.get(key);
		cache1.put(new Element(key, num));
	}

	/**
	 * 从数据库得到 总的条数
	 * 
	 * @param enterpriseId
	 * @return
	 */

	private int getCountFromMessage(String enterpriseId) {
		List<QueryCondition> list = new ArrayList<QueryCondition>();
		list.add(new QueryCondition("admin_id", QueryCondition.EQ, enterpriseId));
		list.add(new QueryCondition("hreads", QueryCondition.EQ, false));
		int num = (int) baseService.getRecordCount(NotifyMessage.class, list);
		return num;
	}

	public Resource getResource() {
		return resource;
	}

	public void setBaseService(IBaseService baseService) {
		this.baseService = baseService;
	}

	public void setResource(Resource resource) {
		this.resource = resource;
	}
}
